from fastapi import FastAPI, Response
from fastapi.responses import StreamingResponse, PlainTextResponse, FileResponse
from typing import Iterator
from pathlib import Path
from stage2_advanced.chapter06_advanced.config import settings

app = FastAPI(title="第6章-高级特性与企业实践", version="1.0.0")

@app.on_event("startup")
async def on_start():
    # 初始化资源/连接池等（示例）
    pass

@app.on_event("shutdown")
async def on_stop():
    # 释放资源/flush日志等（示例）
    pass

# 1) 流式输出：实时日志/大文本流/Server-Sent Events 的基础

def generate_lines() -> Iterator[bytes]:
    for i in range(1, 6):
        yield f"line-{i}\n".encode("utf-8")

@app.get("/stream", summary="流式输出示例")
async def stream_text():
    return StreamingResponse(generate_lines(), media_type="text/plain")

# 2) 大文件下载：按块读取，避免占用内存

@app.get("/download", summary="大文件下载示例")
async def download_file(path: str):
    file_path = Path(path)
    if not file_path.exists():
        return PlainTextResponse("file not found", status_code=404)
    return FileResponse(str(file_path), filename=file_path.name)

# 3) 自定义响应类：纯文本、二进制等

@app.get("/plaintext", summary="自定义纯文本响应")
async def plaintext():
    return PlainTextResponse("hello advanced fastapi")

# 4) 路由高级特性（路径参数转换器/子路由建议可参见教程）

@app.get("/items/{item_id}")
async def get_item(item_id: int):
    return {"item_id": item_id, "env": settings.env, "debug": settings.debug}
